package com.yc.spring.jdbc.biz;

import com.yc.spring.jdbc.bean.Account;
import com.yc.spring.jdbc.bean.Record;
import com.yc.spring.jdbc.dao.AccountDao;
import com.yc.spring.jdbc.dao.RecordDao;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
/**
 * value or transactionMananger 用于指定事务管理器的id
 * propagation 定义事务传播行为 默认: REQUIRED
 * isolation  隔离级别
 * timeout      事务超时, 默认-1,表示不限时
 * readOnly     只读事务    (MyBatis 缓存)
 *
 * rollbackForClassName     设置某一个类异常为回滚异常(编译期异常 或 受检异常)
 *      Spring的JDBC 会抛出 DataAccessException ==> RuntimeException 运行时异常
 *      Spring事务管理默认情况下,只会对 RuntimeException 进行回滚
 * noRollbackFor           设置不回滚的异常(运行时异常)
 * noRollbackForClassName
 *
 */
@Transactional(
        rollbackForClassName = "com.yc.spring.jdbc.biz.BizException"
)
public class AccountBiz {

    @Resource
    private AccountDao adao;
    @Resource
    private RecordDao rdao;

    /**
     * 存取款
     *
     * @param account
     */
    public void deposit(Account account) throws BizException {
        adao.updateBalance(account);
        boolean b = true;
        if(b){
            throw new BizException("自定义的编译期异常");
        }
        // int i = 1 / 0;
        Record record = new Record();
        record.setAccountid(account.getAccountid());
        record.setOpmoney(account.getBalance());
        rdao.insert(record);
    }

    public void transfar(Integer accountid1, Integer accountid2, Double money) throws BizException {
        Account account1 = new Account();
        Account account2 = new Account();
        account1.setAccountid(accountid1);
        account1.setBalance( - money);
        account2.setAccountid(accountid2);
        account2.setBalance( + money);
        // 先存款
        deposit(account2);
        // 在取款
        deposit(account1);
    }

}
